﻿/**
 * Cookie相关操作
 * @namespace Cookie
 * @name core.Cookie
 * @static
 */
core.Cookie = {
  /**
   * 获取Cookie内容
   * @name core.Cookie.get
   * @function
   * @grammar core.Cookie.get(name)
   * @param {String} name Cookie键名
   * @remark 兼容了编码为GBK时的Cookie读取失败的问题 2011-7-7 chenbl@lietou.com
   *
   * @return {String} Cookie值
   */
  get: function (name) {
    var nameEQ = name + '=';
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') c = c.substring(1, c.length);
      if (c.indexOf(nameEQ) == 0) {
        var ret;
        try {
          ret = decodeURIComponent(c.substring(nameEQ.length, c.length));
        } catch (e) {
          ret = unescape(c.substring(nameEQ.length, c.length));
        }
        return ret;
      }
    }
    return null;
  },
  /**
   * 设置Cookie内容
   * @name core.Cookie.set
   * @function
   * @grammar core.Cookie.set(name , value[ , days , path , domain , secure])
   * @param {String} name Cookie键名
   * @param {String} value Cookie键值
   * @param {Int} days Cookie有效期天数
   * @param {String} path Cookie有效路径
   * @param {String} domain Cookie有效域
   * @param {Boolean} secure 是否安全Cookie
   * @remark 兼容了编码为GBK时的Cookie读取失败的问题 2011-7-7 chenbl@lietou.com
   */
  set: function (name, value, days, path, domain, secure) {
    var expires;
    if (core.Object.isNumber(days)) {
      var date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      expires = date.toGMTString();
    } else if (core.Object.isString(days)) {
      expires = days;
    } else {
      expires = false;
    }
    document.cookie = name + '=' + encodeURIComponent(value) +
      (expires ? (';expires=' + expires) : '') +
      (path ? (';path=' + path) : '') +
      (domain ? (';domain=' + domain) : '') +
      (secure ? ';secure' : '');
  },
  /**
   * 删除Cookie内容
   * @name core.Cookie.del
   * @function
   * @grammar core.Cookie.del(name[ , path , domain , secure])
   * @param {String} name 要删除的Cookie键名
   * @param {String} path Cookie有效路径
   * @param {String} domain Cookie有效域
   * @param {Boolean} secure 是否安全Cookie
   */
  del: function (name, path, domain, secure) {
    core.Cookie.set(name, '', -1, path, domain, secure);
  }
};
